<?php

namespace app\agent\controller;

use app\common\controller\Agent;

/**
 * 资金明细
 *
 * @icon fa fa-user
 */
class ShopMoneyRecord extends Agent
{

    protected $relationSearch = true;
    protected $multiFields = 'status';

    protected $model = null;
    protected $agent_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('MoneyRecord');
        $agent_info = session('agent');
        $this->agent_id = $agent_info['id'];
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $shop_ids = \app\common\model\Shop::where('agent_id',$this->agent_id)->column('id');
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->with(['shop','orders'])->where($where)->where(['money_record.member_id'=>0,'money_record.agent_id'=>0,'money_record.shop_id'=>['in',$shop_ids],'detail_type'=>['in',[1,4]]])->order($sort, $order)->paginate($limit);

            if (empty($filter['detail_type'])){ //全统计
                $ljcb = $this->model->with(['shop','orders'])->where($where)->where(['money_record.member_id'=>0,'money_record.agent_id'=>0,'money_record.shop_id'=>['in',$shop_ids]])->where('detail_type',1)->order($sort, $order)->sum('money_record.money');
                $ljfy = $this->model->with(['shop','orders'])->where($where)->where(['money_record.member_id'=>0,'money_record.agent_id'=>0,'money_record.shop_id'=>['in',$shop_ids]])->where('detail_type',4)->order($sort, $order)->sum('money_record.money');
                $count = [['name'=>'累计充值金额','value'=>$ljcb],['name'=>'累计余额扣除','value'=>$ljfy]];
            }else{ //按类别统计
                $lj_money = $this->model->with(['shop','orders'])->where($where)->where(['money_record.member_id'=>0,'money_record.agent_id'=>0,'money_record.shop_id'=>['in',$shop_ids]])->where('detail_type',$filter['detail_type'])->order($sort, $order)->sum('money_record.money');
                $arr = ['','累计充值金额','','','累计余额扣除'];
                $name = $arr[$filter['detail_type']];
                $count = [['name'=>$name,'value'=>$lj_money]];
            }
            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>['count'=>$count]);
            return json($result);
        }
        return $this->view->fetch();
    }


}
